﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Common;
using System.Configuration;

namespace EFProviderWrapperToolkit
{
    public static class ConnectionWrapperUtils
    {
        /// <summary>
        /// Create Code First connection
        /// </summary>
        /// <param name="nameOrConnectionString"></param>
        /// <param name="wrapperProviders"></param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
        public static DbConnection CreateConnectionWrapper(string nameOrConnectionString,
            params string[] wrapperProviders)
        {
            if (nameOrConnectionString == null)
                throw new ArgumentNullException("nameOrConnectionString");

            string[] vals = nameOrConnectionString.Split('=');
            string key = vals.Length == 1 ? nameOrConnectionString : vals[1];

            var configConn = ConfigurationManager.ConnectionStrings[key];
            if (configConn == null)
                throw new Exception("Don't have the nameOrConnectionString!");

            var storeConnection = DbProviderFactories.GetFactory(configConn.ProviderName).CreateConnection();

            storeConnection = DbConnectionWrapper.WrapConnection(storeConnection, wrapperProviders);
            storeConnection.ConnectionString = configConn.ConnectionString;
            return storeConnection;
        }

        /// <summary>
        /// Create No Wrapper Connection
        /// </summary>
        /// <param name="nameOrConnectionString"></param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
        public static DbConnection CreateCommonConnection(string nameOrConnectionString )
        {
            if (nameOrConnectionString == null)
                throw new ArgumentNullException("nameOrConnectionString");

            string[] vals = nameOrConnectionString.Split('=');
            string key = vals.Length == 1 ? nameOrConnectionString : vals[1];

            var configConn = ConfigurationManager.ConnectionStrings[key];
            if (configConn == null)
                throw new Exception("Don't have the nameOrConnectionString!");

            var storeConnection = DbProviderFactories.GetFactory(configConn.ProviderName)
                .CreateConnection();
            storeConnection.ConnectionString = configConn.ConnectionString;
            return storeConnection;
        }
    }
}
